package cn.fastoo.common.utils;

import java.math.BigDecimal;

/**
 * 
 * @author daniel.chan
 * 
 */
public class BigDecimalUtil {

	public static void main(String[] args) {
		Double a = 84.89793487534d;
		Double b = 34.88888888888888888888d;
		System.out.println(BigDecimalUtil.sub(a,b));
	}

	/**
	 * 加法运算
	 * 
	 * @param addend
	 *            被加数
	 * @param augend
	 *            加数
	 * @return
	 */
	public static final double add(double addend, double augend) {
		BigDecimal addEnd = round(addend);
		BigDecimal augEnd = round(augend);
		return addEnd.add(augEnd).doubleValue();
	}

	/**
	 * 减法运算
	 * 
	 * @param minuend
	 *            被减数
	 * @param subtrahend
	 *            减数
	 * @return
	 */
	public static final double sub(double minuend, double subtrahend) {
		BigDecimal minuEnd = round(minuend);
		BigDecimal subtrahEnd = round(subtrahend);
		return minuEnd.subtract(subtrahEnd).doubleValue();
	}

	/**
	 * 乘法运算
	 * 
	 * @param multiplier
	 *            被乘数
	 * @param multiplicand
	 *            乘数
	 * @return
	 */
	public static final double mul(double multiplier, double multiplicand) {
		BigDecimal multipLier = round(multiplier);
		BigDecimal multipliCand = round(multiplicand);
		return multipLier.multiply(multipliCand).doubleValue();
	}

	/**
	 * 除法运算
	 * 
	 * @param dividend
	 *            被除数
	 * @param divisor
	 *            除数
	 * @param scale
	 *            精度(小数位数)
	 * @return
	 */
	public static final double div(double dividend, double divisor, int scale) {
		BigDecimal dividEnd = round(dividend);
		BigDecimal divIsor = round(divisor);
		return dividEnd.divide(divIsor, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public static final double div(double dividend, double divisor) {
		BigDecimal dividEnd = round(dividend);
		BigDecimal divIsor = round(divisor);
		return dividEnd.divide(divIsor).doubleValue();
	}

	public static final BigDecimal round(double d) {
		BigDecimal b1 = new BigDecimal(d);
		BigDecimal b2 = new BigDecimal(1);
		return b1.divide(b2, 2, BigDecimal.ROUND_HALF_UP);
	}
}
